package com.smartleanx.module.hrm.mq.bpm;

import com.smartleanx.module.bpm.event.BpmProcessInstanceStatusEvent;
import com.smartleanx.module.bpm.mq.message.BpmStatusEventMessage;
import com.smartleanx.module.hrm.util.WebhookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 流程实例状态监听
 *
 * @author tengcj
 * @since 2024/6/20
 */
@Slf4j
@Component
public class BpmStatusEventConsumer {

    @Resource
    private ApplicationEventPublisher publisher;

    @Resource
    private WebhookService webhookService;

    public static final String QUEUE = "HRM_STATUS_EVENT_QUEUE";
//    public static final String QUEUE = "HRM_STATUS_EVENT_QUEUE_TEST";

    @RabbitListener(
            bindings = @QueueBinding(
                exchange = @Exchange(value = BpmStatusEventMessage.EXCHANGE, type = "fanout", durable = "true"),
                value = @Queue(value = QUEUE, durable = "true"),
                ignoreDeclarationExceptions = "true"
            )
    )
    public void handleBpmStatusEvent(BpmStatusEventMessage message) {
        log.info("[BpmStatusEventConsumer:handleBpmStatusEvent][消息内容({})]", message);
        try {
            BpmProcessInstanceStatusEvent statusEvent = new BpmProcessInstanceStatusEvent(this)
                    .setId(message.getId()).setStatus(message.getStatus()).setComments(message.getComments())
                    .setProcessDefinitionKey(message.getProcessDefinitionKey()).setBusinessKey(message.getBusinessKey())
                    .setBusinessData(message.getBusinessData());
            System.out.println("已推送通知审批通过================33333333333333333");
            publisher.publishEvent(statusEvent);
        } catch (Exception ex) {
            log.error("[BpmStatusEventConsumer:handleBpmStatusEvent]", ex);
            String errMessage = "流程实例状态事件消费失败，消息内容：%s, 错误信息：%s";
            webhookService.sendMessage(String.format(errMessage, message, ex.getMessage()));
        }
    }

}
